package com.training.controller;

import com.training.entity.Class;
import com.training.entity.Course;
import com.training.entity.Student;
import com.training.entity.User;
import com.training.entity.TopicQuestion; // 1. 新增导入
import com.training.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.List;






@Controller
@RequestMapping("/student")
public class StudentController {

    // --- 原有注入保持不变 ---
    @Autowired
    private StudentService studentService;
    @Autowired
    private ClassService classService;
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private PurchaseRecordService purchaseRecordService;
    @Autowired
    private CourseService courseService;
    @Autowired
    private UserService userService;

    // --- 2. 新增注入 QaService ---
    @Autowired
    private QaService qaService;
//    @Autowired
//    private LearningProgressService learningProgressService;

    // ... 您所有其他的方法都保持原样，无需改动 ...
    // ... 此处省略其他方法，只展示被修改的方法 ...

    @GetMapping("/dashboard")
    public String showStudentDashboard(HttpSession session, Model model, RedirectAttributes redirectAttributes) {
        User loggedInUser = (User) session.getAttribute("loggedInUser");
        if (loggedInUser == null || (!"STUDENT".equalsIgnoreCase(loggedInUser.getRole()) && !"ADMIN".equalsIgnoreCase(loggedInUser.getRole()) && !"TEACHER".equalsIgnoreCase(loggedInUser.getRole()))) {
            return "redirect:/login";
        }

        if ("STUDENT".equalsIgnoreCase(loggedInUser.getRole())) {
            Student student = studentService.getStudentByUserId(loggedInUser.getId());
            if (student == null) {
                redirectAttributes.addFlashAttribute("errorMessage", "未找到您的学生资料，请联系管理员。");
                return "redirect:/";
            }
            model.addAttribute("student", student);
            List<Class> enrolledClasses = studentService.getEnrolledClasses(student.getId());
            model.addAttribute("enrolledClasses", enrolledClasses);
        }

        model.addAttribute("loggedInUser", loggedInUser);
        return "student-dashboard";
    }

    @GetMapping("/classes")
    public String showStudentClassesPage(HttpSession session, Model model, RedirectAttributes redirectAttributes) {
        User loggedInUser = (User) session.getAttribute("loggedInUser");
        if (loggedInUser == null || !"STUDENT".equalsIgnoreCase(loggedInUser.getRole())) {
            return "redirect:/login";
        }

        Student student = studentService.getStudentByUserId(loggedInUser.getId());
        if (student == null) {
            redirectAttributes.addFlashAttribute("errorMessage", "未找到您的学生资料。");
            return "redirect:/student/dashboard";
        }

        List<Class> enrolledClasses = studentService.getEnrolledClasses(student.getId());
        model.addAttribute("enrolledClasses", enrolledClasses);
        model.addAttribute("loggedInUser", loggedInUser);

        return "student-classes";
    }

    @GetMapping("/class/{classId}/courses")
    public String showClassCoursesForStudent(@PathVariable("classId") Long classId,
                                             HttpSession session,
                                             Model model,
                                             RedirectAttributes redirectAttributes) {
        User loggedInUser = (User) session.getAttribute("loggedInUser");
        if (loggedInUser == null) {
            return "redirect:/login";
        }

        Student student = studentService.getStudentByUserId(loggedInUser.getId());
        if (student == null) {
            session.invalidate();
            redirectAttributes.addFlashAttribute("error", "学生信息不完整，请联系管理员。");
            return "redirect:/login";
        }

        boolean isStudentEnrolled = classService.isStudentEnrolledInClass(classId, student.getId());
        if (!isStudentEnrolled) {
            redirectAttributes.addFlashAttribute("errorMessage", "您无权查看该班级的课程。");
            return "redirect:/student/dashboard";
        }

        Class classObj = classService.getClassById(classId);
        if (classObj == null) {
            redirectAttributes.addFlashAttribute("errorMessage", "班级不存在。");
            return "redirect:/student/dashboard";
        }

        List<Course> classCourses = classService.getCoursesByClassId(classId);

        model.addAttribute("loggedInUser", loggedInUser);
        model.addAttribute("classObj", classObj);
        model.addAttribute("classCourses", classCourses);

        return "class-courses-for-student";
    }

    @GetMapping("/my-courses")
    public String showStudentMyCoursesPage(HttpSession session, Model model) {
        User loggedInUser = (User) session.getAttribute("loggedInUser");
        if (loggedInUser == null || !"STUDENT".equalsIgnoreCase(loggedInUser.getRole())) {
            return "redirect:/login";
        }
        Student student = studentService.getStudentByUserId(loggedInUser.getId());
        if (student == null) {
            return "redirect:/student/dashboard";
        }

        List<Course> purchasedCourses = purchaseRecordService.getPurchasedCoursesByStudentId(student.getId());
        model.addAttribute("loggedInUser", loggedInUser);
        model.addAttribute("purchasedCourses", purchasedCourses);
        return "student-my-courses";
    }

    @GetMapping("/my-practices")
    public String showStudentMyPracticesPage(HttpSession session, Model model) {
        User loggedInUser = (User) session.getAttribute("loggedInUser");
        if (loggedInUser == null || !"STUDENT".equalsIgnoreCase(loggedInUser.getRole())) {
            return "redirect:/login";
        }
        model.addAttribute("loggedInUser", loggedInUser);
        return "student-my-practices";
    }


    /**
     * 3. 这是被修改的核心方法
     * 显示“我的问答”页面
     */
    @GetMapping("/my-qa")
    public String showStudentMyQaPage(HttpSession session, Model model) {
        User loggedInUser = (User) session.getAttribute("loggedInUser");
        if (loggedInUser == null || !"STUDENT".equalsIgnoreCase(loggedInUser.getRole())) {
            return "redirect:/login";
        }

        // 从 Service 获取数据
        List<TopicQuestion> askedQuestions = qaService.getQuestionsAskedByUser(loggedInUser.getId());
        List<TopicQuestion> answeredQuestions = qaService.getQuestionsAnsweredByUser(loggedInUser.getId());

        // 将数据放入 Model，传递给前端页面
        model.addAttribute("askedQuestions", askedQuestions);
        model.addAttribute("answeredQuestions", answeredQuestions);
        model.addAttribute("loggedInUser", loggedInUser);

        return "student-my-qa";
    }

    @GetMapping("/news")
    public String showStudentNewsPage(HttpSession session, Model model) {
        User loggedInUser = (User) session.getAttribute("loggedInUser");
        if (loggedInUser == null || !"STUDENT".equalsIgnoreCase(loggedInUser.getRole())) {
            return "redirect:/login";
        }
        model.addAttribute("loggedInUser", loggedInUser);
        return "student-news";
    }

    // ... 您所有其他的方法都保持原样，无需改动 ...
    @GetMapping("/courses/browse")
    public String browseAvailableCourses(HttpSession session, Model model) {
        User loggedInUser = (User) session.getAttribute("loggedInUser");
        if (loggedInUser == null || !"STUDENT".equalsIgnoreCase(loggedInUser.getRole())) {
            return "redirect:/login";
        }
        model.addAttribute("loggedInUser", loggedInUser);
        List<Course> availableCourses = courseService.getAllCourses();
        model.addAttribute("availableCourses", availableCourses);
        return "student-browse-courses";
    }

    @PostMapping("/purchase/{courseId}")
    public String purchaseCourse(@PathVariable("courseId") Long courseId,
                                 HttpSession session,
                                 RedirectAttributes redirectAttributes) {
        User loggedInUser = (User) session.getAttribute("loggedInUser");
        if (loggedInUser == null || !"STUDENT".equalsIgnoreCase(loggedInUser.getRole())) {
            return "redirect:/login";
        }
        Student student = studentService.getStudentByUserId(loggedInUser.getId());
        if (student == null) {
            redirectAttributes.addFlashAttribute("errorMessage", "未找到您的学生资料，无法购买课程。");
            return "redirect:/student/courses/browse";
        }

        try {
            boolean success = purchaseRecordService.purchaseCourse(student.getId(), courseId);
            if (success) {
                redirectAttributes.addFlashAttribute("successMessage", "课程购买成功！");
            } else {
                redirectAttributes.addFlashAttribute("errorMessage", "购买课程失败：积分不足或已购买。");
            }
        } catch (RuntimeException e) {
            e.printStackTrace();
            redirectAttributes.addFlashAttribute("errorMessage", "购买课程失败：" + e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            redirectAttributes.addFlashAttribute("errorMessage", "购买课程失败：发生未知错误。");
        }
        return "redirect:/student/my-courses";
    }

    @PostMapping("/cart/purchaseAll")
    public String purchaseAllFromCart(HttpSession session, RedirectAttributes redirectAttributes) {
        User loggedInUser = (User) session.getAttribute("loggedInUser");
        if (loggedInUser == null || !"STUDENT".equalsIgnoreCase(loggedInUser.getRole())) {
            return "redirect:/login";
        }
        Student student = studentService.getStudentByUserId(loggedInUser.getId());
        if (student == null) {
            redirectAttributes.addFlashAttribute("errorMessage", "未找到您的学生资料，无法购买课程。");
            return "redirect:/student/cart";
        }

        List<Course> cartItems = shoppingCartService.getCartItemsByStudentId(student.getId());
        if (cartItems.isEmpty()) {
            redirectAttributes.addFlashAttribute("errorMessage", "购物车为空，无法购买。");
            return "redirect:/student/cart";
        }

        BigDecimal totalCost = BigDecimal.ZERO;
        for (Course course : cartItems) {
            if (course.getCouPrice() != null) {
                totalCost = totalCost.add(course.getCouPrice());
            }
        }

        if (student.getStuScore() < totalCost.intValue()) {
            redirectAttributes.addFlashAttribute("errorMessage", "购买失败：您的积分不足以购买购物车中的所有课程。");
            return "redirect:/student/cart";
        }

        boolean allPurchasedSuccessfully = true;
        for (Course course : cartItems) {
            try {
                boolean success = purchaseRecordService.purchaseCourse(student.getId(), course.getId());
                if (!success) {
                    allPurchasedSuccessfully = false;
                    System.err.println("Failed to purchase course " + course.getCouName() + " for student " + student.getId());
                }
            } catch (RuntimeException e) {
                allPurchasedSuccessfully = false;
                System.err.println("Error purchasing course " + course.getCouName() + ": " + e.getMessage());
            }
        }

        if (allPurchasedSuccessfully) {
            shoppingCartService.clearCartByStudentId(student.getId());
            redirectAttributes.addFlashAttribute("successMessage", "购物车中所有课程购买成功！");
        } else {
            redirectAttributes.addFlashAttribute("errorMessage", "购物车中部分课程购买失败，请检查您的积分或已购买课程。");
        }

        return "redirect:/student/my-courses";
    }

    @GetMapping("/manage")
    public String manageStudents(@RequestParam(value = "name", required = false) String name,
                                 Model model,
                                 HttpSession session,
                                 RedirectAttributes redirectAttributes) {
        User loggedInUser = (User) session.getAttribute("loggedInUser");
        if (loggedInUser == null || (!"ADMIN".equalsIgnoreCase(loggedInUser.getRole()) && !"TEACHER".equalsIgnoreCase(loggedInUser.getRole()))) {
            redirectAttributes.addFlashAttribute("errorMessage", "您没有权限访问学生管理页面。");
            return "redirect:/login";
        }

        List<Student> students;
        if (name != null && !name.trim().isEmpty()) {
            students = studentService.searchStudentsByName(name.trim());
        } else {
            students = studentService.findAllStudents();
        }

        model.addAttribute("students", students);
        model.addAttribute("studentCount", students.size());
        model.addAttribute("searchName", name);
        return "student-manage";
    }

    @GetMapping("/create")
    public String showCreateStudentForm(Model model, HttpSession session, RedirectAttributes redirectAttributes) {
        User loggedInUser = (User) session.getAttribute("loggedInUser");
        if (loggedInUser == null || (!"ADMIN".equalsIgnoreCase(loggedInUser.getRole()) && !"TEACHER".equalsIgnoreCase(loggedInUser.getRole()))) {
            redirectAttributes.addFlashAttribute("errorMessage", "您没有权限创建学生。");
            return "redirect:/login";
        }

        model.addAttribute("student", new Student());
        model.addAttribute("isEdit", false);
        model.addAttribute("username", "");
        return "student-create-edit";
    }

    @PostMapping("/create")
    public String createStudent(@ModelAttribute Student student,
                                @RequestParam("username") String username,
                                @RequestParam("password") String password,
                                RedirectAttributes redirectAttributes,
                                HttpSession session) {
        User loggedInUser = (User) session.getAttribute("loggedInUser");
        if (loggedInUser == null || (!"ADMIN".equalsIgnoreCase(loggedInUser.getRole()) && !"TEACHER".equalsIgnoreCase(loggedInUser.getRole()))) {
            redirectAttributes.addFlashAttribute("errorMessage", "您没有权限创建学生。");
            return "redirect:/login";
        }

        try {
            boolean success = studentService.addStudent(student, username, password);
            if (success) {
                redirectAttributes.addFlashAttribute("successMessage", "学生添加成功！");
            } else {
                redirectAttributes.addFlashAttribute("errorMessage", "学生添加失败，学号或用户名可能已存在。");
            }
        } catch (Exception e) {
            e.printStackTrace();
            redirectAttributes.addFlashAttribute("errorMessage", "学生添加失败：" + e.getMessage());
        }
        return "redirect:/student/manage";
    }

    @GetMapping("/edit/{id}")
    public String showEditStudentForm(@PathVariable("id") Long id, Model model, HttpSession session, RedirectAttributes redirectAttributes) {
        User loggedInUser = (User) session.getAttribute("loggedInUser");
        if (loggedInUser == null || (!"ADMIN".equalsIgnoreCase(loggedInUser.getRole()) && !"TEACHER".equalsIgnoreCase(loggedInUser.getRole()))) {
            redirectAttributes.addFlashAttribute("errorMessage", "您没有权限编辑学生信息。");
            return "redirect:/login";
        }

        Student student = studentService.getStudentById(id);
        if (student == null) {
            redirectAttributes.addFlashAttribute("errorMessage", "学生不存在。");
            return "redirect:/student/manage";
        }
        model.addAttribute("student", student);
        model.addAttribute("isEdit", true);
        User user = userService.getUserById(student.getUserId());
        if (user != null) {
            model.addAttribute("username", user.getUsername());
        } else {
            model.addAttribute("username", "");
        }

        return "student-create-edit";
    }

    @PostMapping("/edit")
    public String editStudent(@ModelAttribute Student student,
                              @RequestParam("username") String username,
                              @RequestParam(value = "password", required = false) String password,
                              RedirectAttributes redirectAttributes,
                              HttpSession session) {
        User loggedInUser = (User) session.getAttribute("loggedInUser");
        if (loggedInUser == null || (!"ADMIN".equalsIgnoreCase(loggedInUser.getRole()) && !"TEACHER".equalsIgnoreCase(loggedInUser.getRole()))) {
            redirectAttributes.addFlashAttribute("errorMessage", "您没有权限编辑学生信息。");
            return "redirect:/login";
        }

        try {
            boolean success = studentService.saveStudent(student, username, password);
            if (success) {
                redirectAttributes.addFlashAttribute("successMessage", "学生信息更新成功！");
            } else {
                redirectAttributes.addFlashAttribute("errorMessage", "学生信息更新失败，学号或用户名可能已存在。");
            }
        } catch (Exception e) {
            e.printStackTrace();
            redirectAttributes.addFlashAttribute("errorMessage", "学生信息更新失败：" + e.getMessage());
        }
        return "redirect:/student/manage";
    }

    @PostMapping("/delete/{id}")
    public String deleteStudent(@PathVariable("id") Long id, RedirectAttributes redirectAttributes, HttpSession session) {
        User loggedInUser = (User) session.getAttribute("loggedInUser");
        if (loggedInUser == null || (!"ADMIN".equalsIgnoreCase(loggedInUser.getRole()) && !"TEACHER".equalsIgnoreCase(loggedInUser.getRole()))) {
            redirectAttributes.addFlashAttribute("errorMessage", "您没有权限删除学生。");
            return "redirect:/login";
        }

        try {
            boolean success = studentService.deleteStudent(id);
            if (success) {
                redirectAttributes.addFlashAttribute("successMessage", "学生删除成功！");
            } else {
                redirectAttributes.addFlashAttribute("errorMessage", "学生删除失败，请稍后再试。");
            }
        } catch (Exception e) {
            e.printStackTrace();
            redirectAttributes.addFlashAttribute("errorMessage", "学生删除失败：" + e.getMessage());
        }
        return "redirect:/student/manage";
    }
//    @GetMapping("/learning-history")
//    public String showLearningHistoryPage(HttpSession session, Model model) {
//        User loggedInUser = (User) session.getAttribute("loggedInUser");
//        if (loggedInUser == null || !"STUDENT".equalsIgnoreCase(loggedInUser.getRole())) {
//            return "redirect:/login";
//        }
//
//        // TODO: 在这里调用服务层获取学习进度和活跃度数据
//        // 例如:
//        // List<CourseActivityDto> courseActivities = learningProgressService.getCourseActivityStats();
//        // model.addAttribute("courseActivities", courseActivities);
//
//        model.addAttribute("loggedInUser", loggedInUser);
//        return "student-learning-history"; // 返回一个新的Thymeleaf模板页面
//    }
}